
<template>
  <el-form ref="form" :model="data" :rules="rules" label-width="80px">
      <el-form-item label="题目" prop="title">
            <el-input v-model.trim="data.title" placeholder="请填写题目" />
      </el-form-item>
      <el-form-item label="图片描述" prop="pic" >
            <el-upload
                :headers ="headerObj"
                :action="$store.state.settings.file_upload_url"
                :limit=1
                list-type="picture-card"
                accept="image/png, image/jpeg, image/gif, image/jpg"
                :on-success="handlepicSuccess"
                :file-list="data.picfileList"
                :before-upload="beforepicUpload"
                :on-exceed="handlepicExceed"
                :on-preview="handlepicPreview"
                :on-remove="handlepicRemove">
                <i class="el-icon-plus"></i>
            </el-upload>
        </el-form-item>  
        <el-form-item label="选项" >
                <el-table
                  border
                  :data="tableData"
                  style="width: 100%">
                  <el-table-column  label="操作"  width="120"  header-align="center">
                        <template slot="header">
                            <el-button  type="primary" size="small" icon="el-icon-plus" @click="addItem()">增加一栏</el-button>
                        </template>
                        <template slot-scope="scope">
                            <el-button  type="danger" size="small" icon="el-icon-delete" @click="remove_item(scope.$index)">删除</el-button>
                        </template>
                  </el-table-column>
                  <el-table-column
                   header-align="center"
                    label="选项编号"
                    width="180">
                     <template slot-scope="scope">
                          <el-input v-model="scope.row.option_number" placeholder="选项编号A,B,C"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column
                  header-align="center"
                    label="选项标题">
                    <template slot-scope="scope">
                          <el-input v-model="scope.row.option_name"></el-input>
                    </template>
                  </el-table-column>
                </el-table>
       </el-form-item> 
        <el-form-item label="答案" prop="right_answer">
            <el-input v-model.trim="data.right_answer" placeholder="请填写答案" />
       </el-form-item> 
        <el-form-item label="答案解析" prop="remark">
            <el-input  type="textarea" rows="5" v-model.trim="data.remark"  />
       </el-form-item>            
 
        <el-form-item>
          <el-button type="primary" :disabled="$store.state.settings.ajaxButton" @click="submit">提交</el-button>
        </el-form-item>
         <el-dialog :visible.sync="dialogVisible" width="30%" append-to-body>
              <img width="100%" :src="previewUrl" alt="">
        </el-dialog> 
      </el-form>
       
</template>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
</style>
<script>
import { edit,detail,del_option } from '@/api/question'
import { getToken } from '@/utils/auth'


export default {
  name: 'quesitonEdit',
  components: { },
  props: {
    item: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      loading:false,
      dialogVisible:false,
      previewUrl:'',
      headerObj: {
            'Authorization': 'Bearer ' + getToken()
        },
      rules: {
          title: [
              { required: true, message: '请填写题目', trigger: 'blur' },
              { min: 2, max: 50, message: '题目长度在 2 到 50 个字符', trigger: 'blur' }
          ],
          right_answer: [
              { required: true, message: '请填写正确答案', trigger: 'blur' },
          ],
      },
       tableData: [ //表单数据记录
            {
                option_number:'',
                option_name:'',
                option_id :''
            }
        ],
      data: {
            title:'',
            pic:'',
            right_answer:'',
            remark:'',
            picfileList:[]
      }
    }
  },
created() {
    const id = this.item.id
    this.id = id
    this.fetchData(id)
  },
  watch: {
    item: {
      handler(val, oldVal) {
        if (this.item.dialogVisible === true 
        ) {
          this.id = val.id
          this.fetchData(val.id)
        }
      },
      deep: true
    }
  },
  methods: {
          fetchData(id) {
          detail(id).then(response => {
            this.loading = false;
            this.data = response.data;
            this.data.picfileList=response.data.pic ? response.data.pic.split(',').map(item=>{return{name:item,url:item}}):[];
            this.tableData = response.data.option;
          }).catch(err => {
            console.log(err)
          })
        },
        addItem:function(){
              //表单增加一栏
                this.tableData.push({
                      option_number:'',
                      option_name:''
                  })
          },
          remove_item: function (index) {
               let option_id = this.tableData[index].option_id;
                //删除当前一栏
                del_option(option_id).then(response => {
                    this.$message.success('删除成功');  
                    this.tableData.splice(index, 1)
                }).catch(err => {
                     this.$message.error(err);
                })
            },
            handlepicExceed(){ 
                this.$message.error('只能上传一张图片');
             },
            handlepicPreview(file){
                 this.dialogVisible = true;
                 this.previewUrl = file.url;
             },
            handlepicRemove(){
                 this.data.pic = '';
             },
             handlepicSuccess(response) {
                this.$store.commit('settings/SET_AJAX_BUTTON', false);
                this.data.pic= response.data.src;
            },
             beforepicUpload(file) {
                this.$store.commit('settings/SET_AJAX_BUTTON', true);
                const isJPG = file.type === "image/jpeg";
                const isPNG = file.type === "image/png";
                const isLt5M = file.size / 1024 / 1024 < 5;
                if (!isJPG && !isPNG) {
                this.$message.error("上传图片只能是 JPG 、PNG格式!");
                }
                if (!isLt5M) {
                this.$message.error("上传图片大小不能超过 2MB!");
                }
                
            },
  

    
    submit() {
 
      const thiz = this

      this.$refs.form.validate(valid => {
        if (!valid) {
          return false
        }
        edit(this.data).then(response => {
          this.$store.commit('settings/SET_AJAX_BUTTON', true);
          this.$message({
            message: '编辑成功',
            type: 'success',
            duration: 1500,
            onClose() {
              if (thiz.$refs.form !== undefined) {
                thiz.$refs.form.resetFields()
              }
                thiz.item.dialogVisible = false
            }
          })
        })
      })
    }
  }
}
</script>
